package com.eranga.project;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.eranga.project.control.data.AreaCoordinatesDS;
import com.eranga.project.control.data.AreaDS;
import com.eranga.project.model.Area;
import com.eranga.project.model.AreaCoordinates;

public class LoginActivity extends Activity implements OnClickListener{

	EditText login_Vehicle_no,login_password;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		Button login_button=(Button) findViewById(R.id.login_button);
		
		login_Vehicle_no=(EditText) findViewById(R.id.login_Vehicle_no);
		login_password = (EditText) findViewById(R.id.login_password);
		
		login_button.setOnClickListener(this);
		
		SharedPreferences localSP;
		String SETTINGS = "SETTINGS";
		localSP = getSharedPreferences(SETTINGS, Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE);

		if(!localSP.getString("Status", "").equals("")){
			Intent intent = new Intent(LoginActivity.this, MainActivity.class);
	        startActivity(intent);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.login_button:
			
				String v_id=login_Vehicle_no.getText().toString();
				String pass=login_password.getText().toString();
				if(!v_id.equals("") && !pass.equals("") )
					new check_user().execute(v_id,pass);
				else
					Toast.makeText(getApplicationContext(),"Please enter a valid Vehicle No & Password", Toast.LENGTH_SHORT).show();
			break;

		default:
			break;
		}
	}

	
	@Override
	protected void onPause() {
	// TODO Auto-generated method stub
		super.onPause();
		finish();
		
	}
	
	ProgressDialog dialog;
	Button login;

	
	
	class check_user extends AsyncTask<String, String, Boolean> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(LoginActivity.this);
			dialog.setMessage("Loading.. Please wait...");
			dialog.setIndeterminate(false);
			dialog.setCancelable(false);
			dialog.show();
		}

		
		protected Boolean doInBackground(String... args) {
			
			try {
			
				String v_id=args[0];
				String pass=args[1];
				
				SharedPreferencesClass.setLocalSharedPreference(getApplicationContext(), "driver_id", v_id.toString());
				SharedPreferencesClass.setLocalSharedPreference(getApplicationContext(), "password", pass.toString());
				
				URL json = new URL("http://smartautomobile.donsej.com/index.php/api/speed_area_map?format=json&vehicleNo="+v_id+"&password="+pass);
				URLConnection jc = json.openConnection();
				BufferedReader readerfdblist = new BufferedReader(new InputStreamReader(jc.getInputStream()));

				String line = "{Data:"+readerfdblist.readLine()+"}";
				
				Log.v("line", line.toString());
				
				JSONObject jsonResponse = new JSONObject(line);
				
				JSONArray jsonArray = jsonResponse.getJSONArray("Data");
				
				Log.v("test", "Array Length Server DB :" + jsonArray.length());
				for (int i = 0; i < jsonArray.length(); i++)
				{
					
					JSONObject jObject = (JSONObject) jsonArray.get(i);
					String area_id = jObject.getString("area_id");
					String area_name = jObject.getString("area_name");
					String area_speed_limit = jObject.getString("area_speed_limit");
					String coordinates = "{coordinates:"+jObject.getString("coordinates")+"}";
					
					Log.v("1", "----------------------");
					Log.v("2", "area_id :"+area_id);
					Log.v("3", "area_name :"+area_name);
					Log.v("4", "area_speed_limit :"+area_speed_limit);
										
					JSONObject jsonResponse1 = new JSONObject(coordinates);
					
					JSONArray jsonArray1 = jsonResponse1.getJSONArray("coordinates");
					
					Area area= new Area();
					area.setAreaName(area_name);
					area.setSpeedLimit(Double.parseDouble(area_speed_limit));
					int areaId= new AreaDS(LoginActivity.this).createArea(area);
					area.setAreaId(areaId);
					
					if(areaId<=0){
						return false;
					}
					
					Log.v("test", "Array Length Server DB :" + jsonArray1.length());
					
					if(jsonArray1.length()==4){
						
						for (int j = 0; j < jsonArray1.length(); j++){
							
							JSONObject jObject1 = (JSONObject) jsonArray1.get(j);
							String latitude = jObject1.getString("latitude");
							String longitude = jObject1.getString("longitude");
							
							AreaCoordinates coordinates1 =new AreaCoordinates();
							coordinates1.setCoordinateLatitude(Double.parseDouble(latitude));
							coordinates1.setCoordinateLongitude(Double.parseDouble(longitude));
							coordinates1.setCoordinateAreaId(areaId);
							int coordinatesId=new AreaCoordinatesDS(LoginActivity.this).createAreaCoordinates(coordinates1);
							coordinates1.setCoordinateId(coordinatesId);
							
							if(coordinatesId<=0){
								return false;
							}
						
						}
				}
					Log.v("4", "----------------------");

					
					
				}

				

			} catch (Exception e) {

				e.printStackTrace();
				return false;
			}

			return true;
		}

		
		protected void onPostExecute(final Boolean status) {
			
			dialog.dismiss();
			
			runOnUiThread(new Runnable() {
				public void run() {
				
					if(status){
						Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_SHORT).show();
						SharedPreferencesClass.setLocalSharedPreference(getApplicationContext(), "Status", "Success");
						Intent intent = new Intent(LoginActivity.this, MainActivity.class);
				        startActivity(intent);
					}else{
						Toast.makeText(getApplicationContext(),"Invalid credentials", Toast.LENGTH_SHORT).show();
					}

				}
			});

		}

	}
	
}
